/**
 * Created by chang on 2017/2/14.
 */
const md5 = require('md5')
const shortid = require('shortid');
const moment = require('moment')

const helper = module.exports

helper.uuid = (dna) => {
    return md5(`${helper.uuid_short()}${Math.random()}`) + (!!dna ? `_${dna}` : '')
}

helper.uuid_short = () => {
    return shortid.generate();
}

helper.now = (fmt) => {
    fmt = fmt || 'YYYY-MM-DD HH:mm:ss'
    return moment().format(fmt)
}

helper.md5 = (msg) => {
    return md5(msg)
}

helper.rdmFlowNo = () => {
    return this.now('YYYYMMDDHHmmss') + Math.floor(Math.random() * 100000)
}

helper.parse = (msg) => {
    return JSON.parse(JSON.stringify(msg))
}

helper.toTimeString = (time, fmt) => {
    if (!time) return ''

    fmt = fmt || 'YYYY-MM-DD HH:mm:ss'
    return moment(time).format(fmt)
}

helper.getQueryString = (name, search) => {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
    let regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
    let results = regex.exec(search)
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '))
}

helper.isCellPhone = (n) => {
    return /^1\d{10}$/.test(n)
}

helper.isEmail = (n) => {
    return /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(n)
}

helper.isPrice = (n) => {
    return /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(n)
}
